﻿using ByteSheep.Events;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventController : MonoBehaviour
{
    public QuickEvent OnBegin;

    public QuickEvent OnFinish;

    public bool AutoRun;

    public float DelayFinishSecond;

    public bool ControlChidren;

    private float _start;

    // Use this for initialization
    private void OnEnable()
    {
        if (AutoRun)
        {
            _start = Time.time;
            Begin();
        }
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        if (AutoRun)
        {
            if (DelayFinishSecond >= 0)
            {
                if (Time.time > _start + DelayFinishSecond)
                {
                    Finish();
                }
            }
        }
    }

    public void Begin()
    {
        OnBegin.Invoke();
        if (ControlChidren)
        {
            EventController[] cs = GetComponentsInChildren<EventController>();
            for (int i = 0; i < cs.Length; i++)
            {
                if (cs[i] != this)
                {
                    cs[i].Begin();
                }
            }
        }
    }

    public void Finish()
    {
        OnFinish.Invoke();
        if (ControlChidren)
        {
            EventController[] cs = GetComponentsInChildren<EventController>();
            for (int i = 0; i < cs.Length; i++)
            {
                if (cs[i] != this)
                {
                    cs[i].Finish();
                }
            }
        }
    }
}